package com.srwl.mytx.adapter;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSONObject;
import com.google.android.material.snackbar.Snackbar;
import com.srwl.mytx.activity.BaseActivity;
import com.srwl.mytx.utils.DateUtils;
import com.srwl.mytx.Constant;
import com.srwl.mytx.EaseConstant;
import com.srwl.mytx.domain.Message;
import com.srwl.mytx.domain.User;
import com.srwl.mytx.Helper;
import com.srwl.mytx.R;
import com.srwl.mytx.RetrofitManager;
import com.srwl.mytx.dao.DBManager;
import com.srwl.mytx.domain.CommonResult;
import com.srwl.mytx.domain.Orders;
import com.srwl.mytx.domain.Topic;
import com.srwl.mytx.parse.UserProfileManager;
import com.srwl.mytx.service.UserService;
import com.srwl.mytx.utils.Utils;
import com.srwl.mytx.activity.ChatActivity;
import com.srwl.mytx.activity.OrderDetailActivity;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import static com.srwl.mytx.activity.ConversationActivity.NotifyActivity.REQUEST_CODE_TO_ORDER_DETAIL;

public class NotifyMessageAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
    private static final String TAG = "NotifyMessageAdapter";
    private Context context;
    private List<Message> messageList;
    private InteractionListener listener;


    public NotifyMessageAdapter(Context context, List<Message> messageList, InteractionListener listener) {
        this.context = context;
        this.messageList = messageList;
        this.listener = listener;
    }

    @Override
    public int getItemViewType(int position) {
        return messageList.get(position).getSubType();
    }

    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        switch (viewType) {

            case Constant.PUSH_MESSAGE_OFFER_TO_TOPIC_SUCCESS:
            case Constant.PUSH_MESSAGE_ORDER_INFO:
                View orderView = LayoutInflater.from(context).inflate(R.layout.notify_message_order_item_layout, parent, false);
                return new OrderViewHolder(orderView);


        }
        return null;
    }

    @Override
    public void onBindViewHolder(@NonNull final RecyclerView.ViewHolder holder, int position) {
        final Message notify = messageList.get(position);
        if (holder instanceof OrderViewHolder) {
            OrderViewHolder viewHolder = (OrderViewHolder) holder;


            Orders order = JSONObject.parseObject(notify.getContent(), Orders.class);
            if (order == null) {
                return;
            }

            if (order.getSellerId().equals(UserProfileManager.getInstance().getLoginUserInfo().getuId())) {
                //联系买家
                viewHolder.tv_contact.setText("联系买家");
                viewHolder.tv_contact.setOnClickListener(v -> contact(order.getuId()));
            } else {
                viewHolder.tv_contact.setText("联系卖家");
                viewHolder.tv_contact.setOnClickListener(v -> contact(order.getSellerId()));
            }
            viewHolder.tv_date.setText(DateUtils.getTimestampString(notify.getCreated()));

            switch (order.getStatus()) {
                case Constant.PUSH_MESSAGE_OFFER_TO_TOPIC_SUCCESS:
                    onOfferSuccess(viewHolder, order);
                    break;
                case Constant.ORDER_STATUS_BUYER_CANCELLED:
                case Constant.ORDER_STATUS_SELLER_CANCELLED:
                case Constant.ORDER_STATUS_SELLER_CANCEL_ON_PAID:
                    onOrderCancel(viewHolder, order);
                    break;
                case Constant.ORDER_SEND_STATUS_RECEIVED:
                    onOrderReceive(viewHolder, order);
                    break;
                case Constant.ORDER_STATUS_REFUNDING:
                    onOrderRefund(viewHolder, order);
                    break;
                case Constant.ORDER_STATUS_AGREE_REFUND:
                    onOrderAgreeRefund(viewHolder, order);
                    break;
                case Constant.ORDER_STATUS_REFUSE_REFUND:
                    onOrderRefuseRefund(viewHolder, order);
                    break;
                case Constant.ORDER_STATUS_PAID:
                    onOrderPaid(viewHolder, order);
                    break;

                case Constant.ORDER_STATUS_CANCEL_REFUND:
                    onOrderCancelRefund(viewHolder);
                    break;

                case Constant.ORDER_STATUS_SENT:
                    onOrderSent(viewHolder);
                    break;

            }
            String topicTitle = order.getTitle();
            Topic topic = order.getTopic();
            if (topic != null) {
                topicTitle = topic.getTitle();
            }
            viewHolder.tv_topicTitle.setText(topicTitle);
            viewHolder.itemView.setOnClickListener(v -> {
                Intent intent = new Intent(context, OrderDetailActivity.class);
                intent.putExtra(Constant.EXTRA_INFO_ORDER, order);
                intent.putExtra("syncOrderData", true);
                ((Activity) context).startActivityForResult(intent, REQUEST_CODE_TO_ORDER_DETAIL);
            });

        }

    }






    private void onOrderCancelRefund(OrderViewHolder viewHolder) {
        viewHolder.tv_title.setText("退款已取消");
        viewHolder.tv_content.setText("买家已经取消退款");
    }

    private void onOrderSent(OrderViewHolder viewHolder) {
        viewHolder.tv_title.setText("订单已发货");
        viewHolder.tv_content.setText("卖家已经发货，注意查收");
    }

    private void onOrderPaid(OrderViewHolder viewHolder, Orders order) {
        viewHolder.tv_title.setText("买家已付款");
        viewHolder.tv_content.setText("买家已付款，请尽快发货");
    }

    private void onOfferSuccess(OrderViewHolder viewHolder, Orders order) {
        viewHolder.tv_title.setText("竞价成功");
        String expireTime = "";
        if (order.getExpiryDate() != null) {
            expireTime = DateUtils.getTimestampString(order.getExpiryDate());
        }
        String contentOffer = "您需要在过期日期：" + expireTime + " 之前完成支付，否则保证金将会被扣除";
        viewHolder.tv_content.setText(contentOffer);
    }

    private void onOrderRefuseRefund(OrderViewHolder viewHolder, Orders order) {
        viewHolder.tv_title.setText("拒绝退款");
        viewHolder.tv_content.setText("卖家拒绝退款,您可以进入退款详情，酌情修改后重新发起退款或取消退款；提示：充分的沟通是解决问题的关键");
    }

    private void contact(String targetUserId) {
        User userInfo = Helper.getInstance().queryUserInfoById(targetUserId);
        if (userInfo != null) {
            context.startActivity(new Intent(context, ChatActivity.class).putExtra(EaseConstant.EXTRA_TARGET_USER_INFO, userInfo));
        } else {
            getFullUserInfo(targetUserId);
        }
    }


    private void onOrderAgreeRefund(OrderViewHolder viewHolder, Orders order) {
        viewHolder.tv_title.setText("同意退款");
        viewHolder.tv_content.setText("卖家同意退款，退款金额：" + Utils.moneyFormat(order.getRefund()));


    }

    private void onOrderRefund(OrderViewHolder viewHolder, Orders order) {
        viewHolder.tv_title.setText("退款申请");
        String expireTime = "";
        if (order.getExpiryDate() != null) {
            expireTime = DateUtils.getTimestampString(order.getExpiryDate());
        }
        String content = "买家申请退款，退款金额：" + Utils.moneyFormat(order.getRefund()) + ",您需要在过期日期：" + expireTime + " 之前做出处理，否则视为同意退款；提示：充分的沟通是解决问题的关键";
        viewHolder.tv_content.setText(content);

    }

    private void onOrderReceive(OrderViewHolder viewHolder, Orders order) {
        viewHolder.tv_title.setText("交易成功");
        String content;
        if (order.getRefund() == null) {
            content = "买家已确认收货，订单总金额：" + Utils.moneyFormat(order.getAmount()) + " 已转至您的账户余额";
        } else {
            content = "买家已确认收货，订单总金额：" + Utils.moneyFormat(order.getAmount()) + " ,减去退款金额：" + Utils.moneyFormat(order.getRefund()) + " 后，剩余：" + Utils.moneyFormat(order.getAmount() - order.getRefund()) + "已转至您的账户余额";
        }
        viewHolder.tv_content.setText(content);
    }

    private void onOrderCancel(OrderViewHolder viewHolder, Orders order) {
        viewHolder.tv_title.setText("订单取消");
        viewHolder.tv_topicTitle.setText(order.getTitle());
        String content = "";
        if (order.getStatus() == Constant.ORDER_STATUS_BUYER_CANCELLED) {
            if (order.getType() == Constant.ORDER_TYPE_TO_AUCTION_TOPIC) {
                content = "买家取消订单，交易终止，已扣除订单保证金至您的账户余额";
            } else {
                content = "买家取消订单，交易终止";
            }
        } else if (order.getStatus() == Constant.ORDER_STATUS_SELLER_CANCELLED) {
            content = "卖家取消订单，交易终止";
        } else if (order.getStatus() == Constant.ORDER_STATUS_SELLER_CANCEL_ON_PAID) {
            content = "卖家取消订单，交易终止，订单金额已全额返还至账户余额";
        }
        viewHolder.tv_content.setText(content);
    }

    private void getFullUserInfo(String userId) {
        if (!Helper.getInstance().isNetworkConnected()) {
            ((BaseActivity)context).showToast_v1(context.getString(R.string.network_anomalies));
            return;
        }
        RetrofitManager.getInstance().createRequest(UserService.class)
                .getUserInfo(userId)
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        CommonResult result = response.body();
                        if (!response.isSuccessful() || result == null) {
                            Log.e(TAG, "onResponse: " + response.message());
                            // showToast(tv_customerService, getString(R.string.system_busy));
                            return;
                        }
                        JSONObject object = (JSONObject) result.getData();
                        //把用户作为临时联系人 保存在数据库
                        User userInfo = object.toJavaObject(User.class);
                        userInfo.setType(Constant.USER_TYPE_TEMP);
                        DBManager.getInstance().getDaoSession().getUserDao().insertOrReplace(userInfo);
                        context.startActivity(new Intent(context, ChatActivity.class).putExtra(EaseConstant.EXTRA_TARGET_USER_INFO, userInfo));

                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {
                        Log.e(TAG, "onFailure: " + t.getMessage());
                        // showToast(tv_customerService, getString(R.string.system_busy));
                    }
                });


    }


    @Override
    public int getItemCount() {
        return messageList.size();
    }


    public class OrderViewHolder extends RecyclerView.ViewHolder {
        @BindView(R.id.tv_title)
        TextView tv_title;
        @BindView(R.id.tv_topic_title)
        TextView tv_topicTitle;
        @BindView(R.id.tv_content)
        TextView tv_content;
        @BindView(R.id.tv_contact)
        TextView tv_contact;
        @BindView(R.id.tv_date)
        TextView tv_date;

        public OrderViewHolder(@NonNull View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);

        }
    }







    public interface InteractionListener {
        void showForwardDetail(String forwardId);
    }

    /**
     * 弹出提示
     */
    public void showToast(String message) {
        View view = ((Activity) context).getWindow().getDecorView();
        showToast(view, message);
    }

    public void showToast(final View view, final String toastContent) {
        ((Activity) context).runOnUiThread(new Runnable() {
            public void run() {
                // Toast.makeText(BaseActivity.this, toastContent, Toast.LENGTH_SHORT).show();
                // Snackbar.make(getWindow().getDecorView(), toastContent, Snackbar.LENGTH_LONG).show(); //这样虽然方便了，不用传view 参数进来，弊端：当键盘打开的时候，键盘会遮住Snackbar;
                Snackbar.make(view, toastContent, Snackbar.LENGTH_LONG).show();
            }
        });
    }


}
